const express = require('express');
const router = express.Router();

// feedback
router.get('/',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            res.locals.filter, 
            {
                Owner: req.user.id
            },
        );

        res.locals.fields = [
            'LastUpdateDate',
            'Status',
            '单位',
            '内容',
            '姓名',
            '意见',
            '联系方式',            
        ];
        res.locals.options = {
            sort: { LastUpdateDate: 'desc' },
            lean: true
        };

        return next();
    },
    router.FindDocuments('feedback'),
);

router.post('/',
    async (req, res, next) => {
        if (!req.body.姓名 || !req.body.内容) {
            await res.makeError(400);
            return next();
        }

        // check captcha
        const { captcha, id : cid } = req.body.captcha || {};
        if (!captcha || !cid) {
            res.makeError(400);
            return next('route');
        }

        const captchaCache = await res.app.cache.get(`captcha_${cid}`);
        if ((captchaCache || '').toLowerCase() !== captcha.toLowerCase()) {
            res.makeError(400, 'Captcha code is incorrect!');
            return next('route');
        }

        const feedbackFlow = await res.app.models['flow'].findOne({ Code: 'feedback' });

        if (!feedbackFlow) {
            await res.makeError(400, '此功能尚未启用！');
            return next();
        }

        res.locals.body = req.body;
        res.locals.body.CurrentStep = 2;
        res.locals.body.Status = '0';
        res.locals.body.Flow = feedbackFlow.id;

        res.locals.body.Steps = [null, {
            StartDate: new Date(),
            Status: '1',
        }, {
            StartDate: new Date(),
            Status: '0',
        }]

        if (req.user) {
            res.locals.body.Owner = req.user.id;
        }

        res.locals.fields = [
            '姓名',
            '联系方式',
            '单位',
            '内容',
            
            'Owner',
            'CurrentStep',
            'Status',
            'Flow',
            'Steps',
        ]

        return next();
    },
    router.CreateDocument('feedback')
);

module.exports = router;
